﻿using Bogus;
using Dapper;
using Dapper.Abstractions;
using Dapper.Bulk;

namespace DataAccess.Api.Endpoints.Blog;

public class Meerge : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        // 批量合并示例
        app.MapPost("/api/blogs/bulk-merge", async (IDbConnectionFactory dbConnectionFactory) =>
        {
            using var connection = await dbConnectionFactory.CreateConnectionAsync();

            // 获取一些现有博客ID以更新
            const string selectIdsSql = "SELECT id FROM blogs LIMIT 50";
            var existingIds = (await connection.QueryAsync<int>(selectIdsSql)).ToList();

            // 生成包含现有和新ID的博客列表
            var blogsToMerge = new List<Models.Blog>();

            // 添加现有ID的博客（将更新）
            foreach (var id in existingIds)
            {
                blogsToMerge.Add(new Models.Blog
                {
                    Id = id,
                    Url = new Faker().Internet.Url()
                });
            }

            // 添加新博客（将插入）
            var newBlogs = new Faker<Models.Blog>()
                .RuleFor(p => p.Url, f => f.Internet.Url())
                .Generate(50);

            blogsToMerge.AddRange(newBlogs);

            // 配置实体映射
            BulkManager.Entity<Models.Blog>()
                .Table("blogs")
                .Identity(x => x.Id)
                .UseBulkOptions(options =>
                {
	                options.BatchSize = 1000;
                });

            await connection.BulkMergeAsync(blogsToMerge);
            return Results.Ok($"Successfully merged {blogsToMerge.Count} blogs ({existingIds.Count} updated, {newBlogs.Count} inserted)");
        })
        .WithName("MergeBlogs")
        .WithTags(Tags.Blog);
        
    }
}
